package gpslmall

import (
    "fmt"
	//"bytes"
	"strings"
	"io/ioutil"
	"net/http"
	"net/url"
	"crypto/md5"
	"encoding/json"
	"github.com/astaxie/beego"
)

type BaseRsp struct {
   Success	  bool	  `json:"success"`    //
   ReturnCode string  `json:"returnCode"` //
   ErrorMsg   string  `json:"errorMsg"`   //
}

type Auth struct {
	requrl     string
	shopKey    string
	appsecret  string
}

func NewSDK(restURL,shopKey,appsecret string) *Auth {
	return &Auth{requrl:restURL,shopKey:shopKey,appsecret:appsecret}
}

func (this *Auth) Request(method string,request,response interface{}) ([]byte, error) {
    var requestStr string
    if request != nil {
	    requestbyte, err := json.Marshal(request)
		if err != nil {
			return nil, err
		}
		requestStr = string(requestbyte)
	}
	urlParams := url.Values{}
	urlParams.Add("_mt", method)
	urlParams.Add("_sm", "md5")
	urlParams.Add("_vc", "1.0")
	urlParams.Add("shopKey", this.shopKey)
	if len(requestStr) > 0 {
	   urlParams.Add("request", requestStr)
	}
	sign := makeSign(this.shopKey, this.appsecret, requestStr)
    urlParams.Add("sign", sign)
	body := strings.NewReader(urlParams.Encode())
	//
	beego.Debug("gpsl req:", urlParams)
	//
	reqHttp, err := http.NewRequest("POST", this.requrl, body)
	if err != nil {
		return nil, err
	}
	reqHttp.Header.Set("Content-Type", "application/x-www-form-urlencoded") //必须
	client := &http.Client{}
	resp, err := client.Do(reqHttp)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	beego.Debug("rsp data:", string(data))
	err = json.Unmarshal(data, &response)
	if err != nil {
	    return nil, err
	}	
	return data, nil
}

func makeSign(shopKey, appsecret, request string) string {
	str := shopKey + request + appsecret
	return fmt.Sprintf("%x", md5.Sum([]byte(str)))
}
